package cc.cc4414.cc02.core.controller;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenStore;

import cc.cc4414.cc02.system.entity.User;

/**
 * 基础Controller，其他的Controller都要继承这个类
 * 
 * @author cc 2018年6月5日
 */
public class BaseController {

	@Autowired
	private TokenStore tokenStore;

	/**
	 * 获取当前登录用户信息
	 * 
	 * @return 当前用户
	 */
	public User getUser() {
		User user = new User();
		UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		BeanUtils.copyProperties(userDetails, user);
		return user;
	}

	/**
	 * 移除用户的token(AccessToken以及RefreshToken)
	 * 
	 * @param authentication
	 *            通过authentication查找对应的token
	 */
	public void removeToken(Authentication authentication) {
		OAuth2AccessToken accessToken = tokenStore.getAccessToken((OAuth2Authentication) authentication);
		OAuth2RefreshToken refreshToken = accessToken.getRefreshToken();
		tokenStore.removeAccessTokenUsingRefreshToken(refreshToken);
		tokenStore.removeRefreshToken(refreshToken);
	}

}
